package cn.imvc.data.util;

import java.util.Map;

public class JpqlUtil {
	public static String toWhere(Map<String, String> params) {
		StringBuilder where = new StringBuilder();
		if (params != null && !params.isEmpty()) {
			String first = "1=1";
			for (String key : params.keySet()) {
				String value = params.get(key).trim().replaceAll(".*([';]+|(--)+).*", " ");
				if (!value.equals("")) {
					String field = key.replace("_and_", " and ")
							.replace("_or_", " or ").replace("_not_", " not ")
							.replace("_dot_", ".").replace("_eq", "=")
							.replace("_ne", "!=").replace("_lt", "<")
							.replace("_gt", ">").replace("_le", "<=")
							.replace("_ge", ">=").replace("_like", " like \'%")
							.replace("_number", " ").replace("_boolean", " ")
							.replace("_string", "\'")
							.replace("_date", "to_date(\'");

					char lastChar = field.charAt(field.length() - 1);
					if (lastChar == '\'') {
						field += value + "\'";
						if (field.charAt(field.length() - 2) == '(') {
							field += field + ",\'yyyy-mm-dd')";
						}
					} else if (lastChar == '%') {
						field += value + "%\'";
					} else if (lastChar == ' ') {
						field += value;
					}

					if (field.charAt(0) != ' ') {
						first = field;
					} else {
						where.append(field);
					}
				}
			}
			where.insert(0, " where "+first);
		}
		System.out.println(where.toString());
		return where.toString();
	}

}
